package com.ticket.system.service.impl;

import java.io.IOException;
import java.rmi.ServerException;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.ticket.common.constant.PerformConstants;
import com.ticket.common.core.domain.entity.SysUser;
import com.ticket.common.core.domain.model.LoginUser;
import com.ticket.common.utils.DateUtils;
import com.ticket.common.utils.Id2Utils;
import com.ticket.common.utils.SecurityUtils;
import com.ticket.system.domain.YanchuScore;
import com.ticket.system.domain.vo.StorageAndBatchVO;
import com.ticket.system.domain.vo.StorageCardUserVO;
import com.ticket.system.domain.vo.UserInfoVo;
import com.ticket.system.mapper.*;
import com.ticket.system.service.ITYanchuPointsRuleService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ticket.system.domain.YanchuUserInfo;
import com.ticket.system.service.IYanchuUserInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-10-09
 */
@Service
public class YanchuUserInfoServiceImpl implements IYanchuUserInfoService 
{
    private static final Logger logger = LoggerFactory.getLogger(YanchuUserInfoServiceImpl.class);
    @Autowired
    private YanchuUserInfoMapper yanchuUserInfoMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private YanchuMovieCardMapper yanchuMovieCardMapper;
    @Autowired
    private YanchuStorageCradMapper yanchuStorageCradMapper;

    @Autowired
    private ITYanchuPointsRuleService yanchuPointsRuleService;

    @Autowired
    private YanchuScoreMapper yanchuScoreMapper;

    /**
     * 查询绑定用户
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public YanchuUserInfo selectYanchuUserInfoById(Long id)
    {
        return yanchuUserInfoMapper.selectYanchuUserInfoById(id);
    }
    @Override
    public YanchuUserInfo selectUserInfoByUserId(Long userId)
    {
        if(null==userId){
            return null;
        }
        return yanchuUserInfoMapper.selectUserInfoByUserId(userId);
    }

    /**
     * pc会员列表
     *
     * @param userName
     * @param phone
     * @param sex
     * @return
     */
    @Override
    public List<StorageCardUserVO> getUserList(String userName, String phone, Integer sex) {
        return yanchuUserInfoMapper.getUserList(userName,phone,sex);
    }

    /**
     * 小程序获取储值卡余额和可用观演卡数量
     *
     * @param userId
     * @return
     */
    @Override
    public StorageAndBatchVO getStorageAndBatch(Long userId) {
        StorageAndBatchVO vo = new StorageAndBatchVO();
        vo.setBatch(yanchuMovieCardMapper.getStorageAndBatch(userId));
        vo.setStorage(yanchuStorageCradMapper.getStorageAndBatch(userId));

        YanchuScore yanchuScore = new YanchuScore();
        yanchuScore.setWxUserId(userId);
        List<YanchuScore> yanchuScores = yanchuScoreMapper.selectYanchuScoreList(yanchuScore);
        if(CollectionUtils.isNotEmpty(yanchuScores)){
            vo.setScore(yanchuScores.get(0).getScore());
        }else {
            vo.setScore(0);
        }
        return vo;
    }

    /**
     * 查询绑定用户列表
     * 
     * @param yanchuUserInfo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<YanchuUserInfo> selectYanchuUserInfoList(YanchuUserInfo yanchuUserInfo)
    {
        return yanchuUserInfoMapper.selectYanchuUserInfoList(yanchuUserInfo);
    }

    /**
     * 新增绑定用户
     * 
     * @return 结果
     */
    @Override
    public int insertYanchuUserInfo(UserInfoVo userInfoVo) throws IOException
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        JSONObject jsonObj = Id2Utils.postData(userInfoVo.getUserName(),userInfoVo.getIdNumber());
        if(null==jsonObj || !jsonObj.getString("respCode").equals(PerformConstants.IDCARD_SUCCESS)){
            throw new ServerException("校验失败！");
        }
        YanchuUserInfo yanchuUserInfo = new YanchuUserInfo();
        yanchuUserInfo.setUserName(userInfoVo.getUserName());
        yanchuUserInfo.setIdNumber(userInfoVo.getIdNumber());
        yanchuUserInfo.setIdType(userInfoVo.getIdType());
        yanchuUserInfo.setCreateTime(DateUtils.getNowDate());
        return yanchuUserInfoMapper.insertYanchuUserInfo(yanchuUserInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public YanchuUserInfo authUserInfo(UserInfoVo userInfoVo, LoginUser loginUser) throws IOException
    {
        YanchuUserInfo userInfo = new YanchuUserInfo();
        userInfo.setIdType(userInfoVo.getIdType());
        userInfo.setIdNumber(userInfoVo.getIdNumber());
        YanchuUserInfo userInfoDb = yanchuUserInfoMapper.selectAuthUserInfo(userInfo);
        if(null == userInfoDb){
            JSONObject jsonObj = Id2Utils.postData(userInfoVo.getUserName(),userInfoVo.getIdNumber());
            if(null==jsonObj || !jsonObj.getString("respCode").equals(PerformConstants.IDCARD_SUCCESS)){
                throw new ServerException("校验失败！");
            }
            logger.debug("authUserInfo:{}",jsonObj.toJSONString());
            userInfoDb = new YanchuUserInfo();
            userInfoDb.setUserName(userInfoVo.getUserName());
            userInfoDb.setIdNumber(userInfoVo.getIdNumber());
            userInfoDb.setIdType(userInfoVo.getIdType());
            userInfoDb.setCreateTime(DateUtils.getNowDate());
            yanchuUserInfoMapper.insertYanchuUserInfo(userInfoDb);
            yanchuPointsRuleService.addPoints(4,null,loginUser.getUser().getUserId());
        }else if(!userInfoDb.getUserName().equals(userInfoVo.getUserName())){
            throw new ServerException("校验失败！");
        }else{
            SysUser sysUserDb = sysUserMapper.selectUserAuth(userInfoDb.getId());
            if(null != sysUserDb && !sysUserDb.getUserId().equals(loginUser.getUser().getUserId())){
                throw new ServerException("系统中已存在认证记录！");
            }
        }
        int count = sysUserMapper.updateUserAuth(loginUser.getUser().getUserId(),1,userInfoDb.getId());
        if(count == 0){
            throw new ServerException("认证失败，请不要重复认证！");
        }

        return userInfoDb;
    }

    @Override
    public YanchuUserInfo authUserInfo(Integer idType,String idNumber,String userName) throws IOException
    {
        YanchuUserInfo userInfo = new YanchuUserInfo();
        userInfo.setIdType(idType);
        userInfo.setIdNumber(idNumber);
        userInfo.setUserName(userName);
        YanchuUserInfo userInfoDb = yanchuUserInfoMapper.selectAuthUserInfo(userInfo);
        if(null == userInfoDb){
            if(!PerformConstants.ID_TYPE_2.equals(idType)){//护照
                JSONObject jsonObj = Id2Utils.postData(userName,idNumber);
                if(null==jsonObj || !jsonObj.getString("respCode").equals(PerformConstants.IDCARD_SUCCESS)){
                    throw new ServerException("校验失败！");
                }
                logger.debug("authUserInfo:{}",jsonObj.toJSONString());
            }
            userInfoDb = new YanchuUserInfo();
            userInfoDb.setUserName(userName);
            userInfoDb.setIdNumber(idNumber);
            userInfoDb.setIdType(idType);
            userInfoDb.setCreateTime(DateUtils.getNowDate());
            yanchuUserInfoMapper.insertYanchuUserInfo(userInfoDb);
        }
        return userInfoDb;
    }

    /**
     * 修改绑定用户
     * 
     * @param yanchuUserInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateYanchuUserInfo(YanchuUserInfo yanchuUserInfo)
    {
        yanchuUserInfo.setUpdateTime(DateUtils.getNowDate());
        return yanchuUserInfoMapper.updateYanchuUserInfo(yanchuUserInfo);
    }

    /**
     * 批量删除绑定用户
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteYanchuUserInfoByIds(Long[] ids)
    {
        return yanchuUserInfoMapper.deleteYanchuUserInfoByIds(ids);
    }

    /**
     * 删除绑定用户信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteYanchuUserInfoById(Long id)
    {
        return yanchuUserInfoMapper.deleteYanchuUserInfoById(id);
    }
}
